package com.ant.storage.controller;


import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.DepDto;
import com.ant.storage.pojo.CashbookType;
import com.ant.storage.service.ICashbookTypeService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author melon
 * @since 2023-11-10
 */
@RestController
@RequestMapping("/cashbookType")
public class CashbookTypeController {


    @Autowired
    private ICashbookTypeService typeService;

    @ApiOperation(value = "获取物品库存数据列表")
    @GetMapping("/list")
    public ResultVo list(DepDto dto) {
        List<CashbookType> list = typeService.list();
        //        获取根节点
        List<CashbookType> Departments = list.stream()
                .filter(e -> e.getPid()==0)
                .map(e -> {
                    if(getTreeChildren(e, list).size()>0){
                        e.setChildren(getTreeChildren(e, list));
                    }else{
                        e.setChildren(null);
                    }

                    return e;
                }).collect(Collectors.toList());
        return ResultVo.success("获取成功",Departments);

    }


    private List<CashbookType> getTreeChildren(CashbookType e, List<CashbookType> list) {
        List<CashbookType> children = list.stream()
                .filter(m -> Objects.equals(e.getId(), m.getPid()))
                .map(m -> {
                    if(getTreeChildren(m, list).size()>0){
                        m.setChildren(getTreeChildren(m, list));
                    }else {
                        m.setChildren(null);
                    }
                    return m;
                }).collect(Collectors.toList());
        return children;
    }

    @ApiOperation(value = "保存主体")
    @PostMapping("/save")
    public ResultVo save(@RequestBody CashbookType type) {
        if (type.getId() == null) {
            typeService.save(type);
        } else {
            typeService.updateById(type);
        }
        return ResultVo.success("获取成功");
    }

}
